local tskdo=require'zsvc.tskdo'
module(..., package.seeall)

local TaskDisp = {}
local TaskDisp_mt = {__metatable = {}, __index = TaskDisp}

function MakeInhMT(ch)
	ch=ch or {}
	for _i,_j in pairs(TaskDisp) do
		ch[_i]=_j
	end
	return ch
end

function new(dal,cfg, logger,childmt)
	local obj=setmetatable({dal=dal,cfg=cfg,logger=logger or zdc.logger.defaultlog}, childmt or TaskDisp_mt)
	return obj
end

function TaskDisp:SpawnTask(tskid,taskdef)
	local tsk=tskdo.new(self.dal,tskid,taskdef)
	local ok,msg=xpcall(function () tsk:dotask() end,debug.traceback)
	if not ok then
		print(tskid,msg)
	end
end

function TaskDisp:poll(maxcnt)
	local ok,r,msg=self.dal:CallNode(user,self.cfg.tskque,'SetRunner',{runner=self.cfg.id,maxcnt=maxcnt})
	if not ok then return nil,r end
	if not r then return nil,msg end
	for k,v in ipairs(r) do
		self:SpawnTask(v.tskid,v.taskdef)
	end
	return #r
end

function TaskDisp:polltskid(tskid)
	local ok,r,msg=self.dal:CallNode(user,self.cfg.tskque,'SetRunner',{runner=self.cfg.id,tskid=tskid})
	if not ok then return nil,r end
	if not r then return nil,msg end
	self:SpawnTask(r.tskid,r.taskdef)
	return 1
end
